<?php

namespace App\Http\Controllers\GarbageCollect;

use App\Models\Garbage\GarbageEvent;
use App\Models\Garbage\GarbageEventFiles;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\Facades\Storage;
use Validator;
/**
 * @group 垃圾分类->监督反馈->问题反馈列表->文件添加
 *
 * 采用 restful api
 *
 * Body Parameters 表示请求的所需要的参数
 *
 * Query Parameters 表示返回参数的名称
 */

class GarbageEventsFilesController extends Controller
{
    /**
     *
     * 请使用post  form-data方式传输图片
     *
     * @bodyParam event_id int required 图片所属的反馈号 外键 垃圾分类->监督反馈->问题反馈
     * @bodyParam file file required 传输的文件 请保证文件只能是 minetype中 audio image video 这三种类型 不支持 txt等文件
     *
     */
    public function store(Request $request){
        $e = genValidate();
        $validator = Validator::make($request->all(),$e);
        if($validator->fails()){
            return response()->json(encodeMsg($validator->errors()->messages(),400),400);
        }
        try{
            $event_id = Request()->input('event_id');
            $event =GarbageEvent::find($event_id);
            if($event == null){
                return response()->json(["message"=>"未找到该事件"],404);
            }
            if(request()->file('file')){
                $file = new GarbageEventFiles();
                $file->event_id = $event_id;
                $file->file_type=1;
                $file->save();
                $this->fileHandler($request,$file);
            }
            return response()->json(encodeMsg($file,201),201);
        }catch (QueryException $e){
            return response()->json(encodeMsg(["message"=>"添加图片失败".$e->getMessage()],500),500);
        }
    }
    //判断文件类型
    private function detectFileType($file){
        $fileType = array('video'=>2,'image'=>1,'audio'=>3);
        $type = $file->getClientMimeType();
        $type_num = 0;
        foreach ($fileType as $k=>$v){
            if(strpos($type,$k) === 0){
               $type_num = $v;
               break;
            }
        }
        if($type_num == 0){
            return response()->json(encodeMsg(["message"=>"非法文件类型"],400),400);
        }
        return $type_num;
    }
    private function fileHandler($request,$obj){
        $file = $request->file('file');
        if(!$file->isValid()){

            return response()->json(encodeMsg(["message"=>"文件非法"],400),400);
        }

        $ext = $file->getClientOriginalExtension();
        $type = $this->detectFileType($file);
        $realPath = $file->getRealPath();
        $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
        $bool = Storage::disk('local')->put($filename, file_get_contents($realPath));
        if(!$bool){
            return response()->json(encodeMsg(["message"=>"文件存储失败 请联系管理员"],500),500);
        }
        $obj->file_url = $filename;
        $obj->file_type = $type;
        $obj->save();
        return true;
    }

}